package com.huibo.shopping.product.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huibo.shopping.domain.Brand;
import com.huibo.shopping.product.service.BrandService;
import com.huibo.shopping.util.AjaxResult;
import com.huibo.shopping.util.PageQuery;
import com.huibo.shopping.util.PageResult;
import com.huibo.shopping.util.StrUtils;

@RestController
@RequestMapping("/brand")
public class BrandController {

	@Autowired
	private BrandService bs;
	
	@PostMapping("/selectBrand")
	private PageResult<Brand> selectBrand(@RequestBody PageQuery pageQuery) {
		IPage<Brand> ipage = bs.page(new Page<Brand>(pageQuery.getPage(),pageQuery.getRows()),
				new QueryWrapper<Brand>().like("name", pageQuery.getKeyworlds())
				.or().like("englishName", pageQuery.getKeyworlds()).orderByDesc("createTime"));
		return new PageResult<Brand>(ipage.getTotal(),ipage.getRecords());
		
	}
	
	@PostMapping("/insertBrand")
	private AjaxResult insertBrand(@RequestBody Brand brand){
		System.err.println(brand);
		try {
			if(brand.getId() == null) {
				//新增
				brand.setCreateTime(System.currentTimeMillis());
				bs.save(brand);
			}else {
				//修改
				bs.updateById(brand);
			}
			return AjaxResult.getInstance().setMsg("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.getInstance().setMsg("保存失败").setCode(500);
		}
	}
	
	@GetMapping("/deleteBrand/{ids}")
	private AjaxResult deleteBrand(@PathVariable("ids") String ids){
		try {
			
			List<Long> l = StrUtils.splitStr2LongArr(ids);
			bs.removeByIds(l);
			System.err.println(l);
			return AjaxResult.getInstance().setMsg("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.getInstance().setMsg("保存失败").setCode(500);
		}
	}
}
